<?php

namespace App\Http\Controllers\Home\Search;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Home\Search\Api\XunSearchApi;
use App\Http\Controllers\CommonApi\CommonApi;
use App\Http\Controllers\Home\Index\Api\IndexApi;
use App\Model\Goods;

class SearchController extends Controller
{   

    //模拟增加goods表索引到迅搜的索引服务器
    public function add()
    {
        // $goods = Goods::select(['id', 'gname', 'price', 'sid', 'pic', 'sales', 'click', 'state'])
        //     ->get()
        //     ->toArray();

        // //测试把分类和品牌都加进去
        // foreach ($goods as &$v) {
        //     $sort = Goods::where('id', $v['id'])
        //         ->first()
        //         ->findSort->sname;
        //     $v['sortname'] = $sort;
        // }

        $goods = Goods::join('sort', 'goods.sid', '=', 'sort.id')
            ->join('brand', 'goods.bid', '=', 'brand.id')
            ->select([
                'goods.id as id', 
                'gname', 'price', 
                'sid', 
                'pic', 
                'sales', 
                'click', 
                'goods.state as state', 
                'sort.sname as sortname',
            ])
            ->get()
            ->toArray();

        // dd($goods);

        $xs = new XunSearchApi('goods');

        foreach($goods as $v){

            $xs->addDocumentData($v);
        }
    }

    //模拟修改某个单品的索引到迅搜的索引服务器
    public function update()
    {
        //下面这句测试用,固定修改id=1的商品
        $data = Goods::select(['id', 'gname', 'price', 'sid', 'pic', 'sales', 'click', 'state'])
            ->where('id', 1)
            ->first()
            ->toArray();

        // dd($data);

        $xs = new XunSearchApi('goods');
        $xs->updateDocumentData($data);
    }

    public function doSearch(Request $request, $subject)
    {
        $xs = new XunSearchApi($subject);

        // echo $request->get('keyword');

        //获取搜索的关键词
        if ($request->input('keyword') == '') {

            $keyword = '';
            // dd($keyword);

        } else {

            $keyword = $request->input('keyword');
        }

        //判断排序
        if ( $request->input('sort') == 'price-desc' ) {

            $xs->search->setSort('price', false);

        } else if ( $request->input('sort') == 'price-asc' ) {

            $xs->search->setSort('price', true);

        } else if ( $request->input('sort') == 'sales-desc' ) {

            $xs->search->setSort('sales', false);

        } else if ( $request->input('sort') == 'hot-desc' ) {

            $xs->search->setSort('click', false);
        }

        //判断价格范围
        $from = $request->input('from');
        $to = $request->input('to');
        
        //设置要显示条目上限
        $xs->search->setLimit(1000);  

        //通过迅搜查找商品 
        if ($from >= 0 && $to > 0 && $from <= $to) {

            $search = $xs->doSearch($keyword, 'price', $from, $to);

        } else {

            $search = $xs->doSearch($keyword);
        }

        //获取搜索总条目数
        $count = $xs->countSearchNum();
        // dd($count);
        
        //如果没有搜索到数据,则查看是否拼写错误
        $correctWord = '';  //用于存储修正词,返回到前台
        if ($count <= 0) {
            // dd($count);
            $corrected = $xs->search->getCorrectedQuery();  //获取修正词(返回数组,可能有多个)
            
            // dd($corrected);

            if ($corrected) {

                // dd($corrected);
                
                //如果有修正词,则再次用修正词去调用查询
                //遍历修正词去查询,一旦通过此修正词查询到数据,则跳出循环
                foreach ($corrected as $word) {

                    //设置要显示条目上限
                    $xs->search->setLimit(1000);  

                    if ($from >= 0 && $to > 0 && $from <= $to) {

                        $search = $xs->doSearch($word, 'price', $from, $to);

                    } else {

                        $search = $xs->doSearch($word);
                    }

                    if ( count($search) ) {
                        // dd($search, $word);
                        $correctWord = $word;   //把修正词存储
                        break;      //找到数据就跳出循环
                    }
                }

            }
        }

        // dd($correctWord);

        //通过修正词搜索后,再次获取搜索总条目数
        $count = $xs->countSearchNum();

        // dd($search);
        
        //创建分页
        $goods = [];
        if ($search) {
            //===================  分页,函数的参数3决定每页显示个数  ============================
            $goods = CommonApi::CustomPagination($request, $search, 8);
            $msg = ['code' => '200', 'msg' => '查询成功'];

        } else {

            $msg = ['code' => '404', 'msg' => '没有找到相关的商品'];
        }

        return view('Home/List/ListBySearchGoods', [
            'correctword' => $correctWord,
            'msg' => $msg,
            'goods' => $goods,
            'count' => $count,
            'sort' => $request->input('sort'),
            'from' => $request->input('from'),
            'to' => $request->input('to'),
            'keyword' => $keyword,

        ]);

    }


    public function cleanIndex()
    {   
        //下面的goods要用形参写活,为了测试先固定写goods
        $xs = new XunSearchApi('goods');
        $xs->cleanIndex();
    }

    public function flushIndex()
    {   
        //下面的goods要用形参写活,为了测试先固定写goods
        $xs = new XunSearchApi('goods');
        $xs->flushIndex();
    }

    public function getHotQuery()
    {   
        $xs = new XunSearchApi('goods');
        $words = $xs->getHotQuery();
        // dd($words);
    }


    //把新增加的商品加入到迅搜的索引服务器
    public function addToXunSearch($gid = 1)
    {
        // $gid = 1;
        $goods = Goods::join('sort', 'goods.sid', '=', 'sort.id')
            ->join('brand', 'goods.bid', '=', 'brand.id')
            ->select([
                'goods.id as id', 
                'gname', 'price', 
                'sid', 
                'pic', 
                'sales', 
                'click', 
                'goods.state as state', 
                'sort.sname as sortname',
            ])
            ->where('goods.id', $gid)
            ->first()
            ->toArray();

        // dd($goods);

        $xs = new XunSearchApi('goods');
        $xs->addDocumentData($goods);
        
    }


    //修改商品信息后,更新对应商品在迅搜的索引
    public function updateToXunSearch($gid)
    {   
        // $gid = 2;
        //下面这句测试用,固定修改id=1的商品
        $data = Goods::select(['id', 'gname', 'price', 'sid', 'pic', 'sales', 'click', 'state'])
            ->where('id', $gid)
            ->first()
            ->toArray();

        // dd($data);

        $xs = new XunSearchApi('goods');
        $xs->updateDocumentData($data);
    }

}
